#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int m, n;
    int cutOffTree(vector<vector<int>>& f) {
        m = f.size(), n = f[0].size();
        vector<pair<int, int>> trees;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (f[i][j] > 1)
                    trees.push_back({ i,j });
        sort(trees.begin(), trees.end(),
            [&](const pair<int, int>& p1, const pair<int, int>& p2) {
                return f[p1.first][p1.second] < f[p2.first][p2.second];
            });
        int bx = 0, by = 0;
        int ret = 0;
        for (auto& [a, b] : trees)
        {
            int step = bfs(f, bx, by, a, b);
            if (step == -1) return -1;
            ret += step;
            bx = a, by = b;
        }
        return ret;
    }
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };

    int bfs(vector<vector<int>>& f, int bx, int by, int ex, int ey)
    {
        if (bx == ex && by == ey) return 0;
        queue<pair<int, int>>q;
        vector<vector<int>>vis(m, vector<int>(n, false));
        q.push({ bx,by });
        vis[bx][by] = true;
        int st = 0;
        while (q.size())
        {
            st++;
            int sz = q.size();
            while (sz--)
            {
                auto [a, b] = q.front();
                q.pop();
                for (int k = 0; k < 4; k++)
                {
                    int x = a + dx[k], y = b + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && f[x][y])
                    {
                        if (x == ex && y == ey) return st;
                        q.push({ x,y });
                        vis[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }

};